from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from api.models import Token
import datetime
import pytz
from django.core.cache import cache

class LoginAuth(BaseAuthentication):
    def authenticate(self, request):
        """
        1. 对token设置有效时间
        2. 缓存存储
        :param request:
        :return:
        """
        print(request.META.get("HTTP_AUTHORIZATION"))
        token = request.META.get("HTTP_AUTHORIZATION")


        # 1.校验是否存在token字符串
        # 1.1缓存校验
        user = cache.get(token)
        if user:
            print("缓存校验通过")
            return user,token
        # 1.2数据库校验
        token_obj = Token.objects.filter(key=token).first()
        if not token_obj:
            raise AuthenticationFailed("认证失败")

        # 2.校验是否在有效期内
        print(token_obj.created)
        now = datetime.datetime.now()
        now = now.replace(tzinfo=pytz.timezone("UTC"))
        print(now-token_obj.created)
        delta = now - token_obj.created
        state = delta < datetime.timedelta(hours=1)
        print(delta,state)
        if state:
            # 校验成功，写入缓存
            print(delta.total_seconds())
            delta = datetime.timedelta(hours=1) - delta
            print(delta.total_seconds())
            cache.set(token_obj.key,token_obj.user,min(delta.total_seconds(),3600*1)) # 缓存20分钟
            print("数据库校验成功")
            return token_obj.user,token_obj.key
        else:
            raise AuthenticationFailed("认证超时!")




